﻿using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using HandyControl.Controls;
using HardToolApp.Model;
using HardToolApp.Tool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HardToolApp.ViewModel
{
    class CommVM: PeripheralVM
    {
        
        public RelayCommand SetParamCmd { get; }
        public RelayCommand SendDataCmd { get; }
        public RelayCommand ReadDataCmd { get; }

        public CommVM()
        {
            SetParamCmd = new RelayCommand(SendParam);
            SendDataCmd = new RelayCommand(SendData);
            ReadDataCmd = new RelayCommand(ReadData);
        }

        private void UpdateMsg()
        {
            Send((Peripheral)Model);
        }
        public virtual void SendParam()
        {
            Console.WriteLine("send param "+ ((Communicate)Model).commType.ToString());
            ((Communicate)Model).subCmd = (byte)Communicate.SubCmd.SetParam;
            UpdateMsg();
        }

        public virtual void SendData()
        {
            if (string.IsNullOrEmpty(((Communicate)Model).sendBytes))
            {
                Growl.Warning("发送为空");
                return;
            }
            Console.WriteLine("send data"+ ((Communicate)Model).commType.ToString());
            ((Communicate)Model).subCmd = (byte)Communicate.SubCmd.SendData;
            UpdateMsg();
        }
        public virtual void ReadData()
        {
            Console.WriteLine("read data" + ((Communicate)Model).commType.ToString());
            ((Communicate)Model).subCmd = (byte)Communicate.SubCmd.ReadData;
            UpdateMsg();
        }

        /// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="b"></param>
        public virtual void RecData(byte[] b)
        {
            if (b[5] != (byte)CommStatus.COM_OK)
            {
                string str = ((Communicate)Model).cmdName + " " + Communicate.SubString[b[4]] + " " + EnumExtensions.GetDescription((CommStatus)b[5]);
                USBInfoVM.USBVm.AddMap((b[3] << 8) + b[4], b[5]);
                Growl.Warning(str);
            }
            else
            {
                RecOkData(b);
            }
                
        }

        /// <summary>
        /// 处理成功数据
        /// </summary>
        /// <param name="b"></param>
        public virtual void RecOkData(byte[] b)
        {
            Console.WriteLine("OK");
        }

        // 接收到串口相关
        public override void Rec(object t, byte[] b)
        {
            if (b[3] != (byte)((Communicate)Model).commType)
            {
                return;
            }
            RecData(b);
        }
    }
}
